package com.homelock.common.util;

import org.apache.http.conn.HttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
  * 定期清理无效的http连接
  * @author viruser
  *
  */
public class IdleConnectionEvictor  extends Thread{
    private static final Logger logger = LoggerFactory.getLogger(IdleConnectionEvictor.class);

    private final HttpClientConnectionManager manager;
    private Integer waitTime;
    private Integer idleConTime;
    private volatile boolean shutdown = true;

    public IdleConnectionEvictor(HttpClientConnectionManager manager,Integer waitTime, Integer idleConTime){
        this.manager = manager;
        this.waitTime = waitTime;
        this.idleConTime = idleConTime;
        this.start();
    }

    @Override
    public void run(){
        try {
            if(shutdown){
                synchronized (this){
                    wait(waitTime);
                    manager.closeIdleConnections(idleConTime, TimeUnit.SECONDS);
                    manager.closeExpiredConnections();
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    @PreDestroy
    public void shutdown(){
        shutdown = false;
        synchronized (this){
            notifyAll();
        }
    }


}

